﻿using Common.Infrastructure;
using File.Api.Models;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace File.Api.Utils
{
    public class FileUtils
    {
        public static bool Support(string extendName)
        {
            return extendName == ".doc" || extendName == ".docx" || extendName == ".pdf" || extendName == ".ppt" ||
                   extendName == ".pptx" || extendName == ".xls" || extendName == ".xlsx";
        }

        public static string GetFileName(string strFileName)
        {
            var r = string.IsNullOrEmpty(strFileName) ? string.Empty : strFileName.Split('.')[1];
            return DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Guid.NewGuid().ToString().Substring(0, 6) + (string.IsNullOrEmpty(r) ? string.Empty : ("." + r));
        }

        public static FtpFileParam GetFtpFileParam(IConfiguration configuration)
        {
            var host = configuration["FileConfig:FTP:Host"];
            var port = configuration["FileConfig:FTP:Port"];
            var userName = configuration["FileConfig:FTP:UserName"];
            var password = configuration["FileConfig:FTP:Password"];
            if (string.IsNullOrEmpty(host))
            {
                return null;
            }

            FtpFileParam param = new FtpFileParam()
            {
                Host = host,
                UserName = userName,
                Pasword = password,
                Post = LibSysUtils.ToInt(port)
            };
            if (param.Post == 0)
            {
                param.Post = 21;
            }

            return param;
        }

        public static LocalFileParam GetLocalFileParam(IConfiguration configuration)
        {
            var rootPath = configuration["FileConfig:Local:RootPath"];
            if (string.IsNullOrEmpty(rootPath))
            {
                return null;
            }

            var param = new LocalFileParam()
            {
                RootPath = rootPath
            };
            return param;
        }

        public static int GetLength(string str)
        {
            if (str.Length == 0)
            {
                return 0;
            }

            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
            }

            return tempLen;
        }
    }
}
